package org.example.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.Map;

/**
 * @Auther: GongXl
 * @Date: 2021/3/23 20:26
 * @Description:
 */
@RestController
@RequestMapping
@Api( tags = "验证码")  //swagger分类标题注解
public class KaptchaController {
    @Autowired
    DefaultKaptcha defaultKaptcha;
    /**
     * @Author GongXl
     * @Description 获得验证码
     * @Date 2021/3/24 9:10
     * @Param [httpServletRequest, httpServletResponse]
     * @return void
     **/
    @GetMapping("/captcha")
    @ApiOperation(value = "获得验证码", notes = "暂无")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            //业务逻辑存放code值
            httpServletRequest.getSession().setAttribute("codeValue", createText);
            System.out.println("生成验证码的session:"+httpServletRequest.getSession().getId());
            //设置时间
            httpServletRequest.getSession().setAttribute("codeTime",(new Date()).getTime());
            // 使用生成的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
    /**
     * @Author GongXl
     * @Description 验证验证码是否正确
     * @Date 2021/3/24 9:13
     * @Param [codeValue, httpServletRequest]
     * @return java.util.Map
     **/
    @PostMapping("/checkVerificationCode")
    public Map checkVerificationCode(@RequestParam(value = "codeValue") String codeValue, HttpServletRequest httpServletRequest) {
        String verificationCodeIn = (String) httpServletRequest.getSession().getAttribute("codeValue");
        httpServletRequest.getSession().removeAttribute("verificationCode");
        if (null != verificationCodeIn && verificationCodeIn.length() > 0 && !verificationCodeIn.equals(codeValue)) {

//            return Result.failureMsg("验证码错误，或已失效");
            return null;
        }
        return null;
    }
}